#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging, cgi, os
from datetime import datetime, date
from google.appengine.api import users
from google.appengine.api import oauth
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

class Cashbook(db.Model):
  owner       = db.UserProperty(required=True)
  issue_date  = db.DateTimeProperty()
  summary     = db.StringProperty()
  incomes     = db.FloatProperty(default=0.0)
  expenses    = db.FloatProperty(default=0.0)
  update_timestamp   = db.DateTimeProperty(auto_now=True)
  create_timestamp   = db.DateTimeProperty(auto_now_add=True)

class MainHandler(webapp.RequestHandler):

  def post(self, action, key, format):

    user = users.get_current_user()

    if action == "" and key == "" and format == "" :
      path = os.path.join(os.path.dirname(__file__), 'index.html')
      self.response.out.write(template.render(path, {}))
      # self.response.out.write('Hello world!')
      return;

    xml_data = ''

    ### Show the login user's cashbook
    # ex.) http://localhost:8080/show_all.xml
    if action == "show_all" and format == "xml" :
      query = Cashbook.all().filter('owner =', user).order('issue_date').order('__key__')
      xml_data = "".join(["%s" % t.to_xml() for t in query])
      self.response.set_status(200)


    ### Add or Update an entry to the login user's cashbook
    # ex.) http://localhost:8080/insert.xml?issue_date=2010-06-12&summary=Test Record from api&incomes=120.2&expenses=40.5
    # ex.) http://localhost:8080/update/ahN4dXRhbzE5NzYtZW5naW5lYXBwcg4LEghDYXNoYm9vaxgkDA.xml?issue_date=2010-06-12&summary=Update Record from API&incomes=120.2&expenses=40.5
    if action in ["insert", "update"] and format == "xml" :
      issue_date = self.request.get("issue_date")   # YYYY-MM-DD, ISO 8601 format
      summary = self.request.get("summary")         # string
      incomes = self.request.get("incomes","0.0")   # float
      expenses = self.request.get("expenses","0.0") # float
      try :
        if action == "insert" :
          cb = Cashbook(owner=user)
        else :
          cb = db.get(key)
        cb.issue_date=datetime.strptime(issue_date,"%Y-%m-%d")
        cb.summary=summary
        cb.incomes=float(incomes)
        cb.expenses=float(expenses)
        cb.put()
        xml_data = cb.to_xml()
        self.response.set_status(200)
      except :
        logging.exception('can not insert or update entity ['+key+']')
        self.response.set_status(500)


    ### Show or Delete an entry of the login user's cashbook
    # ex.) http://localhost:8080/show/ahN4dXRhbzE5NzYtZW5naW5lYXBwcg4LEghDYXNoYm9vaxgkDA.xml
    # ex.) http://localhost:8080/delete/ahN4dXRhbzE5NzYtZW5naW5lYXBwcg4LEghDYXNoYm9vaxgjDA.xml
    if action in ["delete", "show"] and format == "xml" :
      try :
        cb = db.get(key)
        xml_data = cb.to_xml()
        if action == "delete" :
          cb.delete()
        self.response.set_status(200)
      except :
        logging.exception('can not show or delete entity ['+key+']')
        self.response.set_status(500)

    result = '<?xml version="1.0" encoding="UTF-8"?>\n<cashbook>\n'+xml_data+'</cashbook>'
    self.response.out.write(result)

  get = post


def main():
  application = webapp.WSGIApplication([('/(.*)(.*)(.*)', MainHandler),
                                        (r'/(show_all|insert)(.*)\.(xml|json)', MainHandler),
                                        (r'/(show|update|delete)/(.*)\.(xml|json)', MainHandler),
                                       ],
                                       debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
